<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Traits\WebDriverTrait;
use Carbon\Carbon;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class ClueController extends Controller
{
    use WebDriverTrait;

    const KST_ID_URL = [
        "922518" => "https://vipz2-hzbk2.kuaishang.cn",
        "873616" => "https://vip5-kf9.kuaishang.cn",
    ];

    public static function sendKst($message, $id, $fi, $cas, $dp = ''): bool
    {
        $serve = env('REMOTE_CHROME');
        $domain = data_get(self::KST_ID_URL, $id);
        if (!$serve || !$domain) {
            Log::error('配置的远程端口有误');
            return false;
        }
        $options = (new ChromeOptions)->addArguments([
            '--no-sandbox',
            '--disable-gpu',
            '--ignore-certificate-errors'
        ]);
        $capabilities = DesiredCapabilities::chrome();
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
        $capabilities->setPlatform('linux');

        $driver = null;

        try {
            $driver = RemoteWebDriver::create(
                $serve,
                $capabilities,
                600000,
                600000
            );
            $dp = urlencode($dp);
            $msg = urlencode($message);
            $url = "{$domain}/bs/im.htm?cas={$cas}___{$id}&fi={$fi}&dp={$dp}&sText=xxl_page&vi=&ism=1&cv={$msg}";
            $driver->get($url);
            $result = static::isExists($driver, WebDriverBy::className("kschatphone_popup_footer"));
            sleep(2);
            $driver->close();
            $driver->quit();
            return $result;
        } catch (\Exception $exception) {
            if ($driver) {
                $driver->close();
                $driver->quit();
            }
            Log::error('获得错误', [
                'message' => $exception->getMessage()
            ]);
        }
        return false;
    }

    public function customerPost(Request $request, $id, $fi, $cas): string
    {
        $msg = $request->get('msg');
        Log::info(' > 1. 自定义接受数据 ', [
            $request->get('info')
        ]);
        if (!$msg) {
            return "Not Message!";
        }

        static::sendKst($msg, $id, $fi, $cas, $request->get('dp', ''));
        return 'OK';
    }

    public function txPost(Request $request, $id, $fi, $cas): string
    {
        $tel = $request->get('leads_tel');
        Log::info(' > 1. 广点通接受数据 ', [
            $id,
            $tel
        ]);
        if (!$tel) return ' not Phone';
        $key = 'gdt_club_' . $tel . $id . $fi .$cas;
        if (!Cache::get($key)) {
            Cache::put($key, 1, 60 * 60 * 25);
            $data = [
                '渠道' => '广点通',
                '位置' => $request->get('tel_location'),
                '名称' => $request->get('leads_name'),
                '电话' => $tel,
                '提交时间' => $request->get('leads_create_time'),
                '广告' => $request->get('campaign_name'),
            ];
            $bundle = [];
            try {
                $val = json_decode($request->get('bundle'), true);
                if ($val)
                    $bundle = $val;
            } catch (\Exception $exception) {

            }

            $msg = collect($data)
                ->merge($bundle)
                ->map(function ($value, $key) {
                    return $key . ' : ' . $value;
                })
                ->join('<br>');

            $sendResult = static::sendKst($msg, $id, $fi, $cas, $request->get('dp', ''));
            if (!$sendResult) {
                Cache::forget($key);
                return 'failed';
            }

        } else {
            Log::info(' > 2. 广点通接受数据 : 数据重复', [
                $tel
            ]);
        }
        return 'OK';
    }

    public function bdPost(Request $request, $id, $fi, $cas): string
    {
        $tel = $request->get('cluePhoneNumber');
        Log::info(' > 1. 百度接受数据 ', [
            $tel
        ]);
        if (!$tel) return ' not Phone';
        $key = 'bd_club_' . $tel. $id . $fi .$cas;

        if (!Cache::get($key)) {
            Cache::put($key, 1, 60 * 60 * 25);

            $data = [
                '渠道' => '基木鱼',
                '位置' => $request->get('area'),
                '电话' => $tel,
                '提交时间' => $request->get('commitTime'),
            ];
            $detail = collect($request->get('formDetail'))->map(function ($val) {
                return $val['name'] . ':' . $val['value'];
            });

            $msg = collect($data)
                ->map(function ($value, $key) {
                    return $key . ' : ' . $value;
                })
                ->merge($detail)
                ->join('<br>');

            $sendResult = static::sendKst($msg, $id, $fi, $cas, $request->get('dp', ''));

            if (!$sendResult) {
                Cache::forget($key);
                return 'failed';
            }

        } else {
            Log::info(' > 2. 百度接受数据 : 数据重复', [
                $tel
            ]);
        }


        return 'OK';
    }

    public function ksPost(Request $request, $id, $fi, $cas): string
    {
        $tel = $request->get('phone');

        Log::info(' > 1. 快手接受数据 ', [
            $tel,
        ]);
        if (!$tel) return ' not Phone';

        $key = 'ks_club_test_' . $tel. $id . $fi .$cas;

        if (!Cache::get($key)) {
            Cache::put($key, 1, 60 * 60 * 25);

            $data = [
                '渠道' => '快手',
                '位置' => $request->get('area'),
                '电话' => $tel,
                '提交时间' => $request->get('create_time_date_time'),
            ];
            $details = collect(data_get($request->get('details'), 'form_details'))
                ->map(function ($item) {
                    return "{$item['key']} : {$item['value']}";
                });
            $msg = collect($data)
                ->map(function ($value, $key) {
                    return $key . ' : ' . $value;
                })
                ->merge($details)
                ->join('<br>');

            $sendResult = static::sendKst($msg, $id, $fi, $cas, $request->get('dp', ''));
            if (!$sendResult) {
                Cache::forget($key);
                return 'failed';
            }
        } else {
            Log::info(' > 2. 快手接受数据 : 数据重复', [
                $tel
            ]);
        }

        return json_encode([
            'code' => '0',
        ]);
    }

    public function hwPost(Request $request, $id, $fi, $cas)
    {
        $tel = $request->get('_手机号') ?? $request->get('_电话');
        if (!$tel) return ' not Phone';
        Log::info(' > 1. 华为接受数据 ', [
            $tel
        ]);
        $data = $request->all();
        $key = 'hw_club_test2_' . $tel. $id . $fi .$cas;
        if (!Cache::get($key)) {
            Cache::put($key, 1, 60 * 60 * 25);
            $dp = $request->get('dp', '');

            $msg = collect($data)
                ->filter(function ($value, $key) {
                    return str_contains($key, '_');
                })
                ->map(function ($value, $key) {
                    return $key . ' : ' . $value;
                })
                ->join('<br>');
            $sendResult = static::sendKst($msg, $id, $fi, $cas, $dp);
            Log::info(' > 2. 华为发送数据 ', [
                $msg, $sendResult
            ]);
            if (!$sendResult) {
                Cache::forget($key);
                return response('fail', 400);
            }

        } else {
            Log::info(' > 2. 华为接受数据 : 数据重复', [
                $tel
            ]);
        }
        return response('ok');
    }

    public function jlPost(Request $request, $id, $fi, $cas): string
    {
        $tel = $request->get('telphone');

        Log::info(' > 1. 巨量飞鱼接受数据 ', [
            $tel
        ]);

        if (!$tel) return ' not Phone';
        $key = 'jl_club_test2_' . $tel. $id . $fi .$cas;

        if (!Cache::get($key)) {
            Cache::put($key, 1, 60 * 60 * 25);

            $toDateTimeString = Carbon::parse((int)$request->get('create_time'))->toDateTimeString();
            $data = collect([
                '渠道' => '巨量飞鱼',
                '位置' => $request->get('area'),
                '姓名' => $request->get('name'),
                '电话' => $tel,
                '微信' => $request->get('weixin'),
                '性别' => $request->get('gender'),
                '年龄' => $request->get('age'),
                '提交时间' => $toDateTimeString,
            ]);
            $msg = $data->merge($request->get('remark_dict'))
                ->map(function ($value, $key) {
                    return $key . ' : ' . $value;
                })
                ->join('<br>');
            Log::info(' > 2. 巨量飞鱼接受数据 : 数据信息', [
                $msg,
            ]);
            $sendResult = static::sendKst($msg, $id, $fi, $cas, $request->get('dp', ''));
            if (!$sendResult) {
                Cache::forget($key);
                return 'failed';
            }

        } else {
            Log::info(' > 2. 巨量飞鱼接受数据 : 数据重复', [
                $tel
            ]);
        }

        return json_encode([
            'code' => 0,
            'message' => 'success'
        ]);
    }

}
